<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------+
// | Treacle PHP Framework Version 0.10                                   |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Treacle.cn All rights reserved.					  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the 'License');      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an 'AS IS' BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the speTreaclefic language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: BoPo <ibopo@126.com>										  |
// +----------------------------------------------------------------------+
/**
 * Treacle Session Class file
 *
 * @author BoPo <ibopo@126.com>
 * @link http://www.treacle.cn/
 * @copyright Copyright &copy; 2007 Treacle
 * @license http://www.treacle.cn/license/
 * @version $Id $
 * @package libraries
 */
/**
 * Session
 *
 * @package libraries
 * @author BoPo <ibopo@126.com>
 * @since 0.10
 * @version	$Id $
 */
class TSession
{
	private $now;
	private $encryption		= TRUE;
	private $use_database	= FALSE;
	private $session_table	= FALSE;
	private $sess_length	= 7200;
	private $sess_cookie	= 'session';
	private $data			= array();
	private $gc_probability	= 5;
	/**
	 * Session Constructor
	 *
	 * The constructor runs the session routines automatically
	 * whenever the class is instantiated.
	 */		
	public function __construct()
	{
		$this->treacle = Treacle::get_instance();
		$this->sess_run();
	}

	/**
	 * Run the session routines
	 *
	 * @access	public
	 * @return	void
	 */		
	public function sess_run()
	{
		/*
		*  Set the "now" time
		*
		* It can either set to GMT or time(). The pref
		* is set in the config file.  If the developer
		* is doing any sort of time localization they
		* might want to set the session time to GMT so
		* they can offset the "last_activity" and
		* "last_visit" times based on each user's locale.
		*
		*/
		if (strtolower(Configure::item('time_reference')) == 'gmt')
		{
			$now = time();
			$this->now = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
			if (strlen($this->now) < 10)
			{
				$this->now = time();
			}
		}
		else
		{
			$this->now = time();
		}
		/*
		*  Set the session length
		*
		* If the session expiration is set to zero in
		* the config file we'll set the expiration
		* two years from now.
		*
		*/
		$expiration = Configure::item('sess_expiration');
		if (is_numeric($expiration))
		{
			if ($expiration > 0)
			{
				$this->sess_length = Configure::item('sess_expiration');
			}
			else
			{
				$this->sess_length = (60*60*24*365*2);
			}
		}
		// Do we need encryption?
		$this->encryption = Configure::item('sess_encrypt_cookie');
		if ($this->encryption == TRUE)
		{
			$this->treacle->load->library('encrypt');
		}
		// Are we using a database?
		if (Configure::item('sess_use_database') === TRUE AND Configure::item('sess_table_name') != '')
		{
			$this->use_database = TRUE;
			$this->session_table = Configure::item('sess_table_name');
			$this->treacle->load->database();
		}
		// Set the cookie name
		if (Configure::item('sess_cookie_name') != FALSE)
		{
			$this->sess_cookie = Configure::item('cookie_prefix').Configure::item('sess_cookie_name');
		}
		/*
		*  Fetch the current session
		*
		* If a session doesn't exist we'll create
		* a new one.  If it does, we'll update it.
		*
		*/
		if ( ! $this->sess_read())
		{
			$this->sess_create();
		}
		else
		{
			// We only update the session every five minutes
			if (($this->data['last_activity'] + 300) < $this->now)
			{
				$this->sess_update();
			}
		}
		// Delete expired sessions if necessary
		if ($this->use_database === TRUE)
		{
			$this->sess_gc();
		}
	}
	/**
	 * Fetch the current session data if it exists
	 *
	 * @access	public
	 * @return	void
	 */
	private function sess_read()
	{
		// Fetch the cookie
		$session = $this->treacle->in->cookie($this->sess_cookie);
		if ($session === FALSE)
		{
			return FALSE;
		}
		// Decrypt and unserialize the data
		if ($this->encryption == TRUE)
		{
			$session = $this->treacle->encrypt->decode($session);
		}
		$session = @unserialize($this->strip_slashes($session));
		if ( ! is_array($session) OR ! isset($session['last_activity']))
		{
			return FALSE;
		}
		// Is the session current?
		if (($session['last_activity'] + $this->sess_length) < $this->now)
		{
			$this->sess_destroy();
			return FALSE;
		}
		// Does the IP Match?
		if (Configure::item('sess_match_ip') == TRUE AND $session['ip_address'] != $this->treacle->in->ip_address())
		{
			$this->sess_destroy();
			return FALSE;
		}
		// Does the User Agent Match?
		if (Configure::item('sess_match_useragent') == TRUE AND $session['user_agent'] != substr($this->treacle->in->user_agent(), 0, 50))
		{
			$this->sess_destroy();
			return FALSE;
		}
		// Is there a corresponding session in the DB?
		if ($this->use_database === TRUE)
		{
			$this->treacle->db->where('session_id', $session['session_id']);

			if (Configure::item('sess_match_ip') == TRUE)
			{
				$this->treacle->db->where('ip_address', $session['ip_address']);
			}
			if (Configure::item('sess_match_useragent') == TRUE)
			{
				$this->treacle->db->where('user_agent', $session['user_agent']);
			}
			$query = $this->treacle->db->get($this->session_table);
			if ($query->num_rows() == 0)
			{
				$this->sess_destroy();
				return FALSE;
			}
			else
			{
				$row = $query->row();
				if (($row->last_activity + $this->sess_length) < $this->now)
				{
					$this->treacle->db->where('session_id', $session['session_id']);
					$this->treacle->db->delete($this->session_table);
					$this->sess_destroy();
					return FALSE;
				}
			}
		}
		// Session is valid!
		$this->data = $session;
		unset($session);
		return TRUE;
	}
	/**
	 * Write the session cookie
	 *
	 * @access	public
	 * @return	void
	 */
	public function sess_write()
	{
		$cookie_data = serialize($this->data);
		if ($this->encryption == TRUE)
		{
			$cookie_data = $this->treacle->encrypt->encode($cookie_data);
		}
		setcookie($this->sess_cookie,$cookie_data,$this->sess_length + time(),Configure::item('cookie_path'),Configure::item('cookie_domain'),0);
	}

	/**
	 * Create a new session
	 *
	 * @access	public
	 * @return	void
	 */
	public function sess_create()
	{
		$sessid = '';
		while (strlen($sessid) < 32)
		{
			$sessid .= mt_rand(0, mt_getrandmax());
		}
		$this->data = array(
		'session_id' 	=> md5(uniqid($sessid, TRUE)),
		'ip_address' 	=> $this->treacle->in->ip_address(),
		'user_agent' 	=> substr($this->treacle->in->user_agent(), 0, 50),
		'last_activity'	=> $this->now
		);
		// Save the session in the DB if needed
		if ($this->use_database === TRUE)
		{
			$this->treacle->db->query($this->treacle->db->insert_string($this->session_table, $this->data));
		}
		// Write the cookie
		$this->data['last_visit'] = 0;
		$this->sess_write();
	}
	/**
	 * Update an existing session
	 *
	 * @access	public
	 * @return	void
	 */
	public function sess_update()
	{
		if (($this->data['last_activity'] + $this->sess_length) < $this->now)
		{
			$this->data['last_visit'] = $this->data['last_activity'];
		}
		$this->data['last_activity'] = $this->now;
		// Update the session in the DB if needed
		if ($this->use_database === TRUE)
		{
			$this->treacle->db->query($this->treacle->db->update_string($this->session_table, array('last_activity' => $this->now), array('session_id' => $this->data['session_id'])));
		}
		// Write the cookie
		$this->sess_write();
	}
	/**
	 * Destroy the current session
	 *
	 * @access	public
	 * @return	void
	 */
	public function destroy()
	{
		setcookie(
		$this->sess_cookie,
		addslashes(serialize(array())),
		($this->now - 31500000),
		Configure::item('cookie_path'),
		Configure::item('cookie_domain'),
		0
		);
	}
	/**
	 * Garbage collection
	 *
	 * This deletes expired session rows from database
	 * if the probability percentage is met
	 *
	 * @access	public
	 * @return	void
	 */
	public function sess_gc()
	{
		srand(time());
		if ((rand() % 100) < $this->gc_probability)
		{
			$expire = $this->now - $this->sess_length;

			$this->treacle->db->where("last_activity < {$expire}");
			$this->treacle->db->delete($this->session_table);
		}
	}
	/**
	 * Fetch a speTreaclefic item form  the session array
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */		
	public function get($item)
	{
		return ( ! isset($this->data[$item])) ? FALSE : $this->data[$item];
	}
	public function all()
	{
		return $this->data;
	}
	/**
	 * Add or change data in the "data" array
	 *
	 * @access	public
	 * @param	mixed
	 * @param	string
	 * @return	void
	 */		
	public function set($newdata = array(), $newval = '')
	{
		if (is_string($newdata))
		{
			$newdata = array($newdata => $newval);
		}

		if (count($newdata) > 0)
		{
			foreach ($newdata as $key => $val)
			{
				$this->data[$key] = $val;
			}
		}

		$this->sess_write();
	}
	/**
	 * Delete a session variable from the "data" array
	 *
	 * @access	array
	 * @return	void
	 */		
	public function delete($newdata = array())
	{
		if (is_string($newdata))
		{
			$newdata = array($newdata => '');
		}
		if (count($newdata) > 0)
		{
			foreach ($newdata as $key => $val)
			{
				unset($this->data[$key]);
			}
		}
		$this->sess_write();
	}
	/**
	 * Strip slashes
	 *
	 * @access	private
	 * @param	mixed
	 * @return	mixed
	 */
	private function strip_slashes($vals)
	{
		if (is_array($vals))
		{
			foreach ($vals as $key=>$val)
			{
				$vals[$key] = $this->strip_slashes($val);
			}
		}
		else
		{
			$vals = stripslashes($vals);
		}
		return $vals;
	}
}
// +--------------------------------------------------------------------------
// |   Last Modified By BoPo
// |   Date: Fri Nov 16 14:05:42 CST 2007
// +--------------------------------------------------------------------------
?>